<template>
	<view>
		<view class="container-flex-auto">
			<!-- 顶部内容 -->
			<u-navbar class="navbarRef" bg-color="transparent">
				<template slot="left">
					<u-icon name="arrow-left" size="32rpx" bold="" color="#fff"
						:label="`第${playingVideoData.episode || 1}集`" label-color="#fff" label-size="32rpx"
						@click="backHandle()" />
				</template>
				<template slot="center" />
			</u-navbar>

			<!-- 中间视频播放 -->
			<view class="content-flex-auto">
				<template v-if="!isAudit">
					<swiper :style="{width: `${windowWidth}px`, height: `${100}%`, backgroundColor: '#000000'}"
						:vertical="true" :current="current" :indicator-dots="false" @animationfinish="animationfinish"
						@change="swiperChange">
						<swiper-item v-for="(list,index) in dataList" :key="list.episode">
							<template v-if="k == index">
								<video v-if="isShow" :id="list.episode + '_' + index" :muted="false" :autoplay="true"
									:enable-play-gesture="true" :enable-auto-rotation="true" :controls="true"
									:show-center-play-btn="true" play-btn-position="center" :http-cache="true"
									:custom-cache="false" :show-play-btn="true" :show-fullscreen-btn="false"
									:show-loading="true" :enable-progress-gesture="true" :src="playingVideoData.video"
									:style="{width: `${windowWidth}px`, height: `${videoHeight}px`, marginTop: `${navHeight}px` }"
									:poster="libraryData.oss_object.url" @play="play(list.state,$event)" @ended="ended"
									@progress="progress" />

								<template v-if="!isShow">
									<image :src="libraryData.oss_object.url" mode="aspectFit"
										:style="{width: `${windowWidth}px`, height: `${videoHeight}px`, marginTop: `${navHeight}px`}"
										@click="coverImageHandle()" />
								</template>

								<!-- 要先判断一下dataList[k+1]是否存在，不存在会报video_src未定义的错误 -->
								<!-- 实现下一个视频的预加载 -->
								<!-- <template v-if="dataList[k+1]" style="width: 0px; height: 0px;">
									<video :id="list.episode + '_pre' + index" :muted="true" :autoplay="false"
										:http-cache="true"
										:src="``"
										:style="'width: 0px; height: 0px;'" @progress="progress2" />
								</template> -->
							</template>
						</swiper-item>
					</swiper>
				</template>

				<template v-if="isAudit">
					<!-- 审核状态下，调用壁纸自定义组件 -->
					<ExaminePanel />
				</template>

				<!-- 右侧可操作栏 -->
				<view class="use-nav">
					<view class="use-item" @click="likeHandle()">
						<view v-show="playingEpisodeItem.is_like === 1">
							<u-image src="/static/images/player-like-red-icon.png" width="64rpx" height="64rpx">
							</u-image>
						</view>
						<view v-show="playingEpisodeItem.is_like === 0">
							<u-image src="/static/images/player-like-icon.png" width="64rpx" height="64rpx"></u-image>
						</view>
						<text>{{ playingEpisodeItem.like_total }}</text>
					</view>
					<view class="use-item" @click="pursuHandle()">
						<view v-show="libraryData.is_pursuing === 1">
							<u-image src="/static/images/player-seek-active-icon.png" width="64rpx" height="64rpx">
							</u-image>
						</view>
						<view v-show="libraryData.is_pursuing === 0">
							<u-image src="/static/images/player-seek-icon.png" width="64rpx" height="64rpx"></u-image>
						</view>
						<text>追剧</text>
					</view>
					<view class="use-item">
						<view class="share-btn">
							<u-button open-type="share" text="分享按钮" shape="circle"></u-button>
						</view>
						<u-image src="/static/images/player-wx-icon.png" width="64rpx" height="64rpx"></u-image>
						<text>分享</text>
					</view>
					<view class="use-item" @click="showGroupHandle()">
						<u-image src="/static/images/player-select-icon.png" width="64rpx" height="64rpx"></u-image>
						<text>选集</text>
					</view>
				</view>

			</view>

			<!-- 最底下的文字部分 -->
			<view class="content-nav" @click="showGroupHandle()">
				<view class="flex ai-center">
					<text class="color-fff font-28">《{{ libraryData.title }}》</text>
					<template v-if="isEnd">
						<u-text :text="`已完结${libraryData.total_plot_num}集全 | 选集`" color="#fff" size="28rpx" />
					</template>
					<template v-else>
						<u-text :text="`更新至${libraryData.update_plot_num}集 | 选集`" color="#fff" size="28rpx" />
					</template>
				</view>
				<u-icon name="arrow-up" color="#fff" size="28rpx" />
			</view>
		</view>

		<!-- 余额支付确认框 -->
		<view class="balance-modal-nav">
			<u-modal :show="balanceModal.show" :z-index="10078" :title="balanceModal.title"
				:content="balanceModal.content" confirm-text="购买" show-cancel-button
				@cancel="balanceModalCancelHandle()" @confirm="balanceModalSubmitHandle()" />
		</view>

		<!-- 选集弹出层 -->
		<PlayerGroup class="recharge-popup-nav" :showGroup.sync="showGroup" :libraryData="libraryData"
			:playerEpisodeNumber="playingEpisodeItem.episode" :allList="allEpisodeList" @resultIndex="resultIndex"
			@needRecharge="needRecharge" @balanceSubmit="balanceSubmit" />

		<!-- 充值弹出层 -->
		<RechargePopup :showPopup.sync="rechargeShow" :video_id="libraryId" :video_name="libraryData.title"
			:episode_id="playingEpisodeItem.episode_id" :episode_number="playingEpisodeItem.episode"
			:episode_price="playingEpisodeItem.episode_price" :shouldContinuePay="true" @success="paySuccess" />

		<!-- 防录屏组件 -->
		<ScreenRecording />
	</view>
</template>

<script>
import ExaminePanel from '@/components/examine-panel/examine-panel.vue'
import ScreenRecording from '@/components/screen-recording/screen-recording.vue'
import PlayerGroup from '@/components/player-group/player-group.vue'
import RechargePopup from '@/components/recharge-popup/recharge-popup.vue'

import {
  queryVideoEpisode,
  queryEpisodeInfo,
  videoLikeVery,
  videoLikeCancel,
  videoPursuingVery,
  videoPursuingCancel,
} from '@/api/index.js'
import { queryBalance } from '@/api/user.js'
import storage from '@/utils/storage.js'
import { CHANNEL_ID } from '@/store/mutation-types.js'

export default {
  components: {
    ExaminePanel,
    ScreenRecording,
    PlayerGroup,
    RechargePopup,
  },
  data() {
    return {
      libraryId: '', // 短剧库Id
      libraryData: {}, // 短剧库数据源
      lastEpisodeId: '', // 观看的最后一集集数Id
      allEpisodeList: [], // 所有剧集库
      playingEpisodeItem: {}, // 正在播放的剧集库dataList[index]
      playingVideoData: {}, // 正在播放的剧集
      balance: '', // 金币余额
      loadTargetEpisodeId: '', // 加载是，需要跳转的剧集id

      recharge: [], // 充值套餐列表
      isShow: false, // 控制视频是否播放，true播放，false展示封面图
      rechargeShow: false, // 充值套餐弹窗
      windowWidth: 0, // 视频宽度
      videoHeight: 0, // 视频组件高度
      dataList: [], // 播放中的剧集库数据，每10条加载一次
      k: 999, // 当前播放剧集数据的下标
      current: 999, // 和k值一起改，模板的值为0 ，但是为0时进来不会自动播放，所以改成3，也可以改成其他数字

      // 选集弹框popup
      showGroup: false,
      navHeight: 64, // 导航栏整体高度

      // 余额支付确认框
      balanceModal: {
        show: false,
        title: '',
        content: '',
        itemData: {},
        index: 0, // 所有剧集库的下标，allEpisodeList[x]
      },
    }
  },
  computed: {
    // true审核模式
    isAudit() {
      return this.$store.state.appConfig.is_ad == 1
    },
    // true已完结
    isEnd() {
      return this.libraryData.is_end == 1
    },
  },
  watch: {
    async k(k, old_k) {
      console.log('k=', k, 'old_k=', old_k)
      console.log('swiper正在播放剧集数据源==', this.dataList)

      this.isShow = false
      const item = this.dataList[k]

      this.playingEpisodeItem = item
      this.lastEpisodeId = item.episode_id
      this.queryEpisodeInfoFn()

      // swiper正在播放剧集，是最后一集，继续加载剧集数据
      if (k == this.dataList.length - 1) {
        this.loadMoreEpisode(item.episode_id)
      }
    },
  },
  async onLoad(option) {
    const {
      library_id,
      episode_id,
      channel_id,
    } = option

    // 之前的渠道Id
    const old_channel_id = storage.get(CHANNEL_ID)

    this.libraryId = Number(library_id)
    if (channel_id) {
      storage.set(CHANNEL_ID, channel_id)
    }
    if (episode_id) {
      this.loadTargetEpisodeId = episode_id
    }

    // uni.showModal({ content: JSON.stringify(option) + '======' })

    // 计算导航栏高度
    this.setNavHeight()

    /**
			 * 
			 * 注意：以下接口都是await同步执行，顺序不可变换
			 * 
			 * */

    // 判断用户是否登录，未登录则自动登录
    // 这里的登录是解决小程序用户直接转发播放页，此时新用户进入小程序不经过首页登录。
    const token = this.$store.state.token
    const new_channel_id = storage.get(CHANNEL_ID)
    if (!token || old_channel_id != new_channel_id) {
      // 未登录或者渠道Id发生变化，请求登录
      await this.getLoginCode()
    }

    // 查用户余额
    await this.queryBalanceFn()

    // 查所有剧集、短剧库详情
    await this.queryAllEpisodeFn()

    // 计算视频高度
    await this.setVideoHight()

  },
  onShow() {},
  onShareAppMessage() {
    const libraryId = this.libraryId
    const last_episode = this.playingVideoData.episode
    // 带上短剧库Id、集数进行分享
    return {
      title: this.libraryData.title, // 默认为小程序名称
      path: `/pages/player/player?library_id=${libraryId}`,
      imageUrl: this.libraryData.oss_object.url // 默认为当前页面的截图
    }
  },
  methods: {
    // 登录
    getLoginCode() {
      return new Promise(resolve => {
        // #ifdef MP-TOUTIAO
        uni.login({
          provider: 'toutiao',
          success: res => {
            const { code } = res
            // 在store/user.js执行登录请求
            this.$store.dispatch('Login', code).then(res => {
              // 获取小程序配置
              this.$store.dispatch('SetAppConfig')
              resolve(res)
            })
          }
        })
        // #endif
      })
    },

    // 查用户余额
    async queryBalanceFn() {
      const data = await queryBalance()
      this.balance = Math.ceil(data.coin)
    },

    // 查所有剧集
    async queryAllEpisodeFn() {
      const {
        episode_list,
        library
      } = await queryVideoEpisode({ vid: this.libraryId })
      this.libraryData = library
      this.allEpisodeList = episode_list

      // 直接加载所有剧集，后续再考虑优化
      this.dataList = this.allEpisodeList

      if (this.loadTargetEpisodeId) {
        // 加载时，有指定跳转到某一集
        const findIndex = this.allEpisodeList.findIndex((item, index) => this.loadTargetEpisodeId == item
          .episode_id)
        this.current = findIndex
        this.k = findIndex
      } else if (library.last_episode_id === 0) {
        // 没有观看历史记录，从第1集开始播放
        this.current = 0
        this.k = 0
      } else {
        // 接口查询到历史记录，从历史记录继续播放
        const findIndex = this.allEpisodeList.findIndex((item, index) => library.last_episode_id == item
          .episode_id)
        if (findIndex !== -1) {
          this.current = findIndex
          this.k = findIndex
        } else {
          // 如果后台删除剧集，再添加剧集，剧集id会发生改变，从第1集开始播放
          this.current = 0
          this.k = 0
        }
      }
    },

    // 查剧集详情信息，未购买会自动购买
    async queryEpisodeInfoFn() {
      queryEpisodeInfo({ episode_id: this.lastEpisodeId }).then(data => {
        const { is_cost } = data
        this.playingVideoData = data

        // 刚刚购买
        if (is_cost === 1) {
          this.dataList[this.k].is_buy = 1
          this.$forceUpdate()
          uni.$u.toast('解锁剧集')
        }

        this.balanceModal = {
          show: false,
          title: '',
          content: '',
          itemData: {},
          index: 0
        }
        this.showGroup = false
        setTimeout(() => {
          // 延迟0.5秒，用户观感更顺滑
          this.isShow = true
        }, 500)
      }).catch(data => {
        uni.$u.toast(data.message)
        this.isShow = false
        this.rechargeShow = true
      })
    },

    // 选集弹出层返回值
    resultIndex(index) {
      this.isShow = false
      // 因为选集跳转，余额不足时，queryEpisodeInfo接口不会返回data，所以手动设置
      this.playingVideoData.episode = this.dataList[index].episode
      this.k = Number(index)
      this.current = Number(index)
    },

    balanceModalCancelHandle() {
      this.balanceModal.show = false
    },

    // 余额支付-购买
    balanceModalSubmitHandle() {
      const {
        index,
        itemData
      } = this.balanceModal

      this.lastEpisodeId = itemData.episode_id
      this.loadMoreJump(index)
    },

    // 显示余额支付确认框
    balanceSubmit(index) {
      // index：所有剧集库下标
      const item = this.allEpisodeList[index]
      const { episode_price } = item
      this.balanceModal.show = true
      this.balanceModal.title = '余额：' + this.balance + '金币',
      this.balanceModal.content = `该集为付费内容，需要【${episode_price}金币】购买`
      this.balanceModal.itemData = item
      this.balanceModal.index = index
    },

    // 支付
    async paySuccess() {
      await this.queryBalanceFn()
      await this.queryEpisodeInfoFn()
    },

    needRecharge() {
      this.rechargeShow = true
    },

    // 计算导航栏高度
    setNavHeight() {
      this.windowWidth = uni.getSystemInfoSync().windowWidth
      // 状态栏高度
      const statusBarHeight = uni.getSystemInfoSync().statusBarHeight
      // #ifdef MP-WEIXIN
      // 获取微信胶囊的位置信息 width,height,top,right,left,bottom
      const custom = uni.getMenuButtonBoundingClientRect()
      // 导航栏高度(标题栏高度) = 胶囊高度 + (顶部距离 - 状态栏高度) * 2
      const navigationBarHeight = custom.height + (custom.top - statusBarHeight - 4) * 2
      // 总体高度 = 状态栏高度 + 导航栏高度
      this.navHeight = navigationBarHeight + statusBarHeight
      // #endif
    },

    // 计算视频高度
    async setVideoHight() {
      // class="content-nav"标签需要接口请求完毕，才渲染才有高度
      const domInfo = uni.createSelectorQuery().in(this).select('.content-nav')
      domInfo.boundingClientRect(data => {
        const { height } = data
        this.videoHeight = uni.getSystemInfoSync().windowHeight - this.navHeight - height
      }).exec()
    },

    // 加载更多剧集数据，每次加载10条
    loadMoreEpisode(lastEpisodeId) {
      const base = 10
      const findIndex = this.allEpisodeList.findIndex(e => lastEpisodeId == e.episode_id)
      const arr = this.allEpisodeList.filter((item, index) => {
        const maxIndex = findIndex + base
        if (index > findIndex && index < maxIndex) return item
      })
      console.log('本次加载的剧集数据==', arr)
      this.dataList = this.dataList.concat(arr)
    },

    // 选集跳转，加载剧集数据
    loadMoreJump(allIndex) {
      // 加载跳转剧集的前后10条，跳转集数90集，加载80集到100集
      const base = 10
      const allLength = this.allEpisodeList.length
      // const item = this.allEpisodeList[allIndex]
      if (allIndex > this.dataList.length - 1) {
        this.dataList = this.allEpisodeList
        //   const arr = this.allEpisodeList.filter((e, e_index) => {
        // if (e_index > startIndex && e_index < endIndex) return e
        //   })
        //   this.dataList = arr

        // 改变k值，会自动去请求购买接口，详见watch
        this.k = allIndex
        this.current = allIndex
      } else {
        // 改变k值，会自动去请求购买接口，详见watch
        this.k = allIndex
        this.current = allIndex
      }
    },

    // 打开选集弹出层
    showGroupHandle() {
      this.showGroup = true
    },

    // 返回上一页
    backHandle() {
      try {
        // webview的堆栈
        // eslint-disable-next-line
					const pages = getCurrentPages()
        // 上一级页面
        const pageUp = pages[pages.length - 2]
        const { fullPath } = pageUp.$page
        const tabbar = ['/pages/watching/watching', '/pages/index/index']
        if (tabbar.includes(fullPath)) {
          uni.switchTab({ url: fullPath })
        } else {
          uni.navigateBack()
        }
      } catch (e) {
        uni.switchTab({ url: '/pages/index/index' })
      }
    },

    ended() {
      if (this.k == this.dataList.length - 1) {
        uni.createVideoContext(this.dataList[this.k].episode + '' + this.k, this).seek(0)
        uni.createVideoContext(this.dataList[this.k].episode + '' + this.k, this).pause()
        uni.showModal({
          content: '已播放完全部剧集',
          showCancel: false,
          confirmText: '返回',
          success(res) {
            if (res.confirm) {
              uni.switchTab({ url: '/pages/index/index' })
            }
          }
        })
      } else {
        this.current = this.k + 1
      }
    },


    // 点击播放&&暂停
    play(state, event) {
      console.log('点击了播放', state)
    },

    // 封面图点击，剧集未解锁封面图会展示
    async coverImageHandle() {
      this.queryEpisodeInfoFn()
    },

    swiperChange(event) {
      const index = event.detail.current

      // 因为选集跳转，余额不足时，queryEpisodeInfo接口不会返回data，所以手动设置
      this.playingVideoData.episode = this.dataList[index].episode

      this.k = index
      // current一定要改，否则会出现选集黑屏的问题
      this.current = index
    },

    // swiper动画结束时会触发animationfinish事件
    animationfinish(event) {
      // 这里进行判断，如果是最后一个视频就加载视频进入列表
      if (this.k == this.dataList.length - 1) {
        // this.GETNEW()
      }
    },

    // 点赞操作
    async likeHandle() {
      const item = this.dataList[this.k]
      const { episode_id } = item

      // item.is_like: 是否已经喜欢 1-喜欢 0-未喜欢
      // true调用取消接口，false调用添加接口
      const isLike = item.is_like == 1

      if (isLike) {
        await videoLikeCancel({ eid: episode_id })
        item.is_like = 0
        item.like_total--
      } else {
        await videoLikeVery({ eid: episode_id })
        item.is_like = 1
        item.like_total++
      }
      // 根据下标改数组，需要强制通知视图更新，vue2.0缺陷
      this.$forceUpdate()
    },

    // 追剧操作
    async pursuHandle() {
      // is_pursuing: 是否已经追剧 1-追剧 0-未追剧
      // true调用取消接口，false调用添加接口
      const isPursuing = this.libraryData.is_pursuing == 1

      if (isPursuing) {
        await videoPursuingCancel({ vid: this.libraryId })
        this.libraryData.is_pursuing = 0
      } else {
        await videoPursuingVery({ vid: this.libraryId })
        this.libraryData.is_pursuing = 1
      }
    },

    // 视频加载进度
    progress(e) {
      console.log('当前视频加载进度=', e.detail.buffered)
    },

    progress2(e) {
      console.log('预加载视频进度=', e.detail.buffered)
    }
  }
}
</script>

<style lang="scss" scoped>
	page {
		background-color: #000000;
	}

	.recharge-popup-nav /deep/ .u-fade-enter-to {
		z-index: 10069 !important;
	}

	.recharge-popup-nav /deep/ .u-slide-up-enter-to {
		z-index: 10074 !important;
	}

	.balance-modal-nav /deep/ .u-fade-enter-to {
		z-index: 10075 !important;
	}

	.balance-modal-nav /deep/ .u-slide-up-enter-to {
		z-index: 10076 !important;
	}

	.use-nav {
		z-index: 999;
		position: absolute;
		bottom: 20%;
		right: 30rpx;
		display: flex;
		flex-direction: column;

		.use-item {
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			margin-top: 36rpx;
			position: relative;

			text {
				color: #fff;
				font-size: 24rpx;
			}

			.share-btn {
				width: 100%;
				height: 100%;
				position: absolute;
				left: 0;
				z-index: 2;
				opacity: 0;

				/deep/ .u-button {
					width: 100%;
					height: 100%;
				}
			}
		}
	}

	.content-nav {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 30rpx 30rpx 90rpx 30rpx;
		background-color: #000000;
	}
</style>
